package edu.unh.sustain;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.util.Log;
import android.util.Xml;

public class VideoFeedParser {

    private static final String TAG         = "VideoFeedParser";

    // names of the XML tags
    static final String         URL         = "url";
    static final String         LINK        = "media:player";
    static final String         DESCRIPTION = "media:description";
    static final String         TITLE       = "media:title";
    static final String         MEDIA_GROUP = "media:group";
    static final String         ENTRY       = "entry";
    static final String         ROOT        = "feed";
    static final String         NAMESPACE   = "http://www.w3.org/2005/Atom";

    private final URL           feedUrl;

    public VideoFeedParser(String feedUrl) {
        try {
            this.feedUrl = new URL(feedUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Video> parse() {
        FeedHandler handler = new FeedHandler();
        Log.d(TAG, "about to parse url");
        try {
            Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, handler);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Log.d(TAG, "returned");
        return handler.getVideos();
    }


    private InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
